/*jslint sloppy: true */
/*global probe, angular */
probe.controller("RoleEdit", function ($scope, $element, privilege, ocAPI, ocDialog) {
	var DI = ocDialog.queryDI($element),
		roleId = DI.share.roleId,
		teamId = DI.share.teamId,
		refreshRoleListOfTeam = DI.share.refreshRoleListOfTeam;

	$scope.role = {
		id: undefined,
		name: '',
		privileges: [],
		comment: ''
	};

	function checkedListToObject(list) {
		var o = {};
		angular.forEach(list, function (id) {
			o[id] = true;
		}, o);
		return o;
	}
	function checkedObjectToList(obj) {
		var l = [];
		angular.forEach(obj, function (isChecked, id) {
			if (isChecked === true) {
				this.push(parseInt(id, 0));
			}
		}, l);
		return l;
	}
	function getRole() {
		ocAPI.use('getRole').by(roleId, teamId).then(function (data) {
			$scope.role = data.role;
			$scope.privilegeChecked = checkedListToObject(data.role.privileges);
			DI.$$scope.title = data.role.name + ' - 角色编辑';
		});
	}
	function done() {
		DI.closeDialog();
		refreshRoleListOfTeam();
	}
	$scope.saveRole = function () {
		var r = $scope.role;
		r.privileges = checkedObjectToList($scope.privilegeChecked);

		if (angular.isDefined(roleId)) {
			ocAPI.use('updateRole').by(roleId, teamId ,r).then(done);
		} else {
			ocAPI.use('createRole').by(r, teamId).then(done);
		}
	};

	$scope.privilegeChecked = {};
	$scope.privilege = privilege;

	// init.
	if (angular.isDefined(roleId)) {
		getRole();
	}

	$scope.fuck = function () {
		console.log($scope.privilegeChecked);
	};
});
